/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "GeometryShader.h"
#include <tinyxml.h>
#include <d3d11.h>
#include "..\Managers\DX11Manager.h"

namespace Hogshead
{
	namespace DX11Rendering
	{
		ContentCPP(Hogshead::DX11Rendering::GeometryShader, GeometryShader)
		GeometryShader::GeometryShader(void)
		{
			_gs = NULL;
			_raw_blob = NULL;
		}


		GeometryShader::~GeometryShader(void)
		{
		}

		void GeometryShader::finalize()
		{
			if(_gs) _gs->Release();
			if(_raw_blob) _raw_blob->Release();
		}

		void GeometryShader::explicitLoad()
		{
			error("You cannot load a GeometryShader in this manor, XML is required");
		}

		void GeometryShader::readXML(const String& in_xml)
		{
		
			//parse the String for what we need
			TiXmlDocument document;
			document.Parse(in_xml);

			TiXmlElement* root_element = document.RootElement();
			String root_tag(root_element->Value());

			if(root_tag.equals("Content"))
			{
				//get the standard stuff
				
				this->_key = String(root_element->Attribute("key"));
				this->_path = String(root_element->Attribute("path"));

				//used to get the absolute path to it 
				this->_path = ContentLibrary::getCompleteContentString( this->_path );

				bool use_stream_output = false;
				int result = root_element->QueryBoolAttribute("useStreamOutput", &use_stream_output);

				if(result == TIXML_WRONG_TYPE)
					error(StringBuilder() << "useStreamOutput unknown value: " << "\n" << _path);

				//get the shader specific stuff
				
				HRESULT h_result = S_OK;
				//the key is the name of the shader, must match with file
				h_result = Shader::CompileShaderFromFile(this->_path, root_element->Attribute("entry"), root_element->Attribute("model"), &_raw_blob);

				if( FAILED( h_result ) )
				{
					MessageBox( NULL, 
						"The Shader file cannot be compiled.  Please run this executable from the directory that contains the FX file.",
						this->_path, 
						MB_OK);

					//release blob
					_raw_blob->Release();
					return;
				}

				if(use_stream_output)
				{
					int stride;
					result = root_element->QueryIntAttribute("stride", &stride);
					if(result != TIXML_SUCCESS)
						error(StringBuilder() << "geometry shader does not have a stride for stream output: " << "\n" << _path);

					TiXmlNode* cur_child = NULL;
					Vector<D3D11_SO_DECLARATION_ENTRY*> sode_vector;
					while(cur_child = root_element->IterateChildren(cur_child))
					{
						TiXmlElement* cur_child_element = cur_child->ToElement();
						if(String(cur_child_element->Value()).equals("SODeclaration"))
						{
							int stream;
							result = cur_child_element->QueryIntAttribute("Stream", &stream);
							if(result != TIXML_SUCCESS)
								error(StringBuilder() << "SODeclaration does not have a stream: " << "\n" << _path);

							const char* semantic_name;
							semantic_name = cur_child_element->Attribute("SemanticName");
							if(!semantic_name)
								error(StringBuilder() << "SODeclaration does not have a semantic_name: " << "\n" << _path);

							int semantic_index;
							result = cur_child_element->QueryIntAttribute("SemanticIndex", &semantic_index);
							if(result != TIXML_SUCCESS)
								error(StringBuilder() << "SODeclaration does not have a SemanticIndex: " << "\n" << _path);

							int start_component;
							result = cur_child_element->QueryIntAttribute("StartComponent", &start_component);
							if(result != TIXML_SUCCESS)
								error(StringBuilder() << "SODeclaration does not have a StartComponent: " << "\n" << _path);

							int component_count;
							result = cur_child_element->QueryIntAttribute("ComponentCount", &component_count);
							if(result != TIXML_SUCCESS)
								error(StringBuilder() << "SODeclaration does not have a ComponentCount: " << "\n" << _path);

							int output_slot;
							result = cur_child_element->QueryIntAttribute("OutputSlot", &output_slot);
							if(result != TIXML_SUCCESS)
								error(StringBuilder() << "SODeclaration does not have an OutputSlot: " << "\n" << _path);

							D3D11_SO_DECLARATION_ENTRY* entry = new D3D11_SO_DECLARATION_ENTRY();
							entry->Stream = stream;
							entry->SemanticName = semantic_name;
							entry->SemanticIndex = semantic_index;
							entry->StartComponent = start_component;
							entry->ComponentCount = component_count;
							entry->OutputSlot = output_slot;

							sode_vector.add(entry);
						}	
					}

					UINT strides[1];
					strides[0] = stride;
					
					Array1D<D3D11_SO_DECLARATION_ENTRY> sode_array(sode_vector.size());
					for(int k = 0; k < sode_array.length(); k++)
					{
						sode_array(k) = *sode_vector[k];
						delete sode_vector[k];
					}


					HRESULT h_result = DX11Manager::createGeometryShaderWithStreamOutput(_raw_blob->GetBufferPointer(),
																_raw_blob->GetBufferSize(),
																(const D3D11_SO_DECLARATION_ENTRY*)sode_array,
																sode_array.length(),
																strides,
																1,
																D3D11_SO_NO_RASTERIZED_STREAM,	
																NULL,
																&this->_gs);
					if(h_result != S_OK)
					{
						error(StringBuilder() << "Geometry Shader with stream output could not be created: \n" << this->_path);
					}
				}
				else
				{

					//create shader
					h_result = DX11Manager::createGSFromBlob(_raw_blob, &_gs);
					if( FAILED( h_result ) )
					{
						MessageBox( NULL, 
						"The Shader file could not be created from byte code.",
						this->_path, 
						MB_OK);
						
						//release blob
						_raw_blob->Release();
						return;
					}
				}
#ifdef _DEBUG
				HRESULT hr = _gs->SetPrivateData( WKPDID_D3DDebugObjectName, _path.length() - 1, _path );
				if(FAILED(hr))
				{
					StringBuilder sb;
					sb << "ERROR ON LOAD: Geometry Shader could not be named: " << _path;
					DX11Manager::_logger->write(sb);
					error(sb);
				}
#endif
				//release blob
				return;
			}

			ContentLibrary::write("XML Schema error in:");
			ContentLibrary::write(this->_path);
			error("Invalid GeometryShader xml file");
			return;
		}
	}
}